from flask import Blueprint, request, jsonify
from app import db
from models.hr import Employee, Payroll, Attendance
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime

bp = Blueprint('hr', __name__, url_prefix='/api/hr')

@bp.route('/employees', methods=['GET'])
@jwt_required()
def get_employees():
    """获取员工列表"""
    try:
        employees = Employee.query.filter_by(is_deleted=False).all()
        return jsonify({
            'code': 200,
            'message': '获取员工列表成功',
            'data': [employee.to_dict() for employee in employees]
        }), 200
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取员工列表失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/employees', methods=['POST'])
@jwt_required()
def create_employee():
    """创建员工"""
    try:
        data = request.get_json()
        
        # 检查必需字段
        required_fields = ['employee_no', 'name', 'hire_date']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必需字段: {field}',
                    'data': None
                }), 400
        
        # 检查员工编号是否已存在
        existing_employee = Employee.query.filter_by(employee_no=data['employee_no']).first()
        if existing_employee:
            return jsonify({
                'code': 400,
                'message': '员工编号已存在',
                'data': None
            }), 400
            
        # 检查身份证号是否已存在
        if 'id_number' in data and data['id_number']:
            existing_id = Employee.query.filter_by(id_number=data['id_number']).first()
            if existing_id:
                return jsonify({
                    'code': 400,
                    'message': '身份证号已存在',
                    'data': None
                }), 400
        
        # 创建新员工
        employee = Employee(
            employee_no=data['employee_no'],
            name=data['name'],
            gender=data.get('gender'),
            birth_date=datetime.strptime(data['birth_date'], '%Y-%m-%d').date() if data.get('birth_date') else None,
            hire_date=datetime.strptime(data['hire_date'], '%Y-%m-%d').date(),
            department=data.get('department'),
            position=data.get('position'),
            phone=data.get('phone'),
            email=data.get('email'),
            address=data.get('address'),
            id_number=data.get('id_number'),
            bank_name=data.get('bank_name'),
            bank_account=data.get('bank_account'),
            status=data.get('status', 'ACTIVE')
        )
        
        db.session.add(employee)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '创建员工成功',
            'data': employee.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'创建员工失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/payrolls', methods=['GET'])
@jwt_required()
def get_payrolls():
    """获取工资列表"""
    try:
        payrolls = Payroll.query.filter_by(is_deleted=False).all()
        return jsonify({
            'code': 200,
            'message': '获取工资列表成功',
            'data': [payroll.to_dict() for payroll in payrolls]
        }), 200
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取工资列表失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/payrolls', methods=['POST'])
@jwt_required()
def create_payroll():
    """创建工资记录"""
    try:
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        # 检查必需字段
        required_fields = ['employee_id', 'pay_period', 'basic_salary']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必需字段: {field}',
                    'data': None
                }), 400
        
        # 检查员工是否存在
        employee = Employee.query.get(data['employee_id'])
        if not employee:
            return jsonify({
                'code': 400,
                'message': '员工不存在',
                'data': None
            }), 400
        
        # 计算应发工资和实发工资
        total_pay = (data['basic_salary'] + 
                    data.get('allowance', 0) + 
                    data.get('bonus', 0) + 
                    data.get('overtime_pay', 0) - 
                    data.get('deduction', 0))
        
        actual_pay = total_pay - data.get('tax', 0)
        
        # 创建工资记录
        payroll = Payroll(
            employee_id=data['employee_id'],
            pay_period=data['pay_period'],
            basic_salary=data['basic_salary'],
            allowance=data.get('allowance', 0),
            bonus=data.get('bonus', 0),
            overtime_pay=data.get('overtime_pay', 0),
            deduction=data.get('deduction', 0),
            tax=data.get('tax', 0),
            total_pay=total_pay,
            actual_pay=actual_pay,
            created_by=current_user_id,
            status=data.get('status', 'DRAFT')
        )
        
        db.session.add(payroll)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '创建工资记录成功',
            'data': payroll.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'创建工资记录失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/attendances', methods=['GET'])
@jwt_required()
def get_attendances():
    """获取考勤列表"""
    try:
        attendances = Attendance.query.filter_by(is_deleted=False).all()
        return jsonify({
            'code': 200,
            'message': '获取考勤列表成功',
            'data': [attendance.to_dict() for attendance in attendances]
        }), 200
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取考勤列表失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/attendances', methods=['POST'])
@jwt_required()
def create_attendance():
    """创建考勤记录"""
    try:
        data = request.get_json()
        
        # 检查必需字段
        required_fields = ['employee_id', 'work_date']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必需字段: {field}',
                    'data': None
                }), 400
        
        # 检查员工是否存在
        employee = Employee.query.get(data['employee_id'])
        if not employee:
            return jsonify({
                'code': 400,
                'message': '员工不存在',
                'data': None
            }), 400
        
        # 创建考勤记录
        attendance = Attendance(
            employee_id=data['employee_id'],
            work_date=datetime.strptime(data['work_date'], '%Y-%m-%d').date(),
            check_in_time=datetime.strptime(data['check_in_time'], '%H:%M:%S').time() if data.get('check_in_time') else None,
            check_out_time=datetime.strptime(data['check_out_time'], '%H:%M:%S').time() if data.get('check_out_time') else None,
            work_hours=data.get('work_hours'),
            overtime_hours=data.get('overtime_hours', 0),
            status=data.get('status', 'PRESENT'),
            remark=data.get('remark')
        )
        
        db.session.add(attendance)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '创建考勤记录成功',
            'data': attendance.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'创建考勤记录失败: {str(e)}',
            'data': None
        }), 500